<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加简历"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="create-resume-dialog">
      <!-- 选择创建方式 -->
      <div class="creation-methods">
        <div class="method-title">选择创建方式</div>
        <div class="method-options">
          <div 
            class="method-card"
            :class="{ active: selectedMethod === 'upload' }"
            @click="selectedMethod = 'upload'"
          >
            <div class="method-icon">
              <el-icon size="32"><Upload /></el-icon>
            </div>
            <div class="method-name">上传简历</div>
            <div class="method-desc">上传已有的Word或PDF简历文件</div>
          </div>

          <div 
            class="method-card"
            :class="{ active: selectedMethod === 'generate' }"
            @click="selectedMethod = 'generate'"
          >
            <div class="method-icon">
              <el-icon size="32"><Edit /></el-icon>
            </div>
            <div class="method-name">在线生成</div>
            <div class="method-desc">通过填写信息自动生成简历</div>
          </div>
        </div>
      </div>

      <!-- 上传简历表单 -->
      <div v-if="selectedMethod === 'upload'" class="upload-form">
        <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" label-width="80px">
          <el-form-item label="简历标题" prop="title">
            <el-input 
              v-model="uploadForm.title" 
              placeholder="请输入简历标题"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="简历文件" prop="file">
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :show-file-list="true"
              :limit="1"
              accept=".pdf,.doc,.docx"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :before-upload="beforeUpload"
            >
              <el-button type="primary">
                <el-icon><Upload /></el-icon>
                选择文件
              </el-button>
              <template #tip>
                <div class="upload-tip">
                  支持 PDF、Word 格式，文件大小不超过 10MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <!-- 在线生成表单 -->
      <div v-if="selectedMethod === 'generate'" class="generate-form">
        <el-form :model="generateForm" :rules="generateRules" ref="generateFormRef" label-width="80px">
          <el-form-item label="简历标题" prop="title">
            <el-input 
              v-model="generateForm.title" 
              placeholder="请输入简历标题"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="选择模板" prop="template">
            <div class="template-selector" v-loading="templateLoading">
              <div 
                v-for="template in templateList"
                :key="template.id"
                class="template-card"
                :class="{ active: generateForm.template === template.id }"
                @click="generateForm.template = template.id"
              >
                <div class="template-preview">
                  <img 
                    v-if="template.preview_image" 
                    :src="template.preview_image" 
                    :alt="template.name"
                  />
                  <div v-else class="template-placeholder">
                    <el-icon><Document /></el-icon>
                  </div>
                </div>
                <div class="template-info">
                  <div class="template-name">{{ template.name }}</div>
                  <div class="template-desc">{{ template.description }}</div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm"
          :loading="creating"
        >
          {{ selectedMethod === 'upload' ? '上传并创建' : '创建简历' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
import { resumeApi, resumeTemplateApi, type ResumeTemplate } from '@/api/resume'

// Props
interface Props {
  modelValue: boolean
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const dialogVisible = ref(false)
const selectedMethod = ref<'upload' | 'generate'>('upload')
const creating = ref(false)
const templateLoading = ref(false)
const templateList = ref<ResumeTemplate[]>([])

// 表单引用
const uploadFormRef = ref<FormInstance>()
const generateFormRef = ref<FormInstance>()
const uploadRef = ref()

// 上传表单
const uploadForm = reactive({
  title: '',
  file: null as File | null
})

// 生成表单
const generateForm = reactive({
  title: '',
  template: null as number | null
})

// 表单验证规则
const uploadRules: FormRules = {
  title: [
    { required: true, message: '请输入简历标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  file: [
    { required: true, message: '请选择简历文件', trigger: 'change' }
  ]
}

const generateRules: FormRules = {
  title: [
    { required: true, message: '请输入简历标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  template: [
    { required: true, message: '请选择简历模板', trigger: 'change' }
  ]
}

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    resetForms()
    if (selectedMethod.value === 'generate') {
      fetchTemplateList()
    }
  }
})

watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 监听创建方式变化
watch(selectedMethod, (val) => {
  if (val === 'generate' && templateList.value.length === 0) {
    fetchTemplateList()
  }
})

// 获取模板列表
const fetchTemplateList = async () => {
  templateLoading.value = true
  try {
    const response = await resumeTemplateApi.getTemplateList()
    const data = response.data || response
    templateList.value = data.results || data || []
  } catch (error) {
    ElMessage.error('获取模板列表失败')
  } finally {
    templateLoading.value = false
  }
}

// 处理文件变化
const handleFileChange = (file: UploadFile) => {
  uploadForm.file = file.raw || null
  
  // 自动设置标题
  if (file.name && !uploadForm.title) {
    const nameWithoutExt = file.name.replace(/\.[^/.]+$/, '')
    uploadForm.title = nameWithoutExt
  }
}

// 处理文件移除
const handleFileRemove = () => {
  uploadForm.file = null
}

// 文件上传前验证
const beforeUpload = (file: File) => {
  const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
  const isValidType = allowedTypes.includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只支持 PDF、Word 格式的文件')
    return false
  }

  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 10MB')
    return false
  }

  return true
}

// 重置表单
const resetForms = () => {
  uploadForm.title = ''
  uploadForm.file = null
  generateForm.title = ''
  generateForm.template = null
  
  uploadFormRef.value?.resetFields()
  generateFormRef.value?.resetFields()
  uploadRef.value?.clearFiles()
}

// 处理确认
const handleConfirm = async () => {
  if (selectedMethod.value === 'upload') {
    await handleUploadConfirm()
  } else {
    await handleGenerateConfirm()
  }
}

// 处理上传确认
const handleUploadConfirm = async () => {
  if (!uploadFormRef.value) return

  try {
    await uploadFormRef.value.validate()
    
    creating.value = true

    // 先创建简历记录
    const resumeData = {
      title: uploadForm.title,
      resume_type: 'uploaded' as const
    }

    const createResponse = await resumeApi.createResume(resumeData)
    const resumeId = createResponse.data?.id || createResponse.id

    // 上传文件
    if (uploadForm.file) {
      const formData = new FormData()
      formData.append('file', uploadForm.file)
      formData.append('title', uploadForm.title)

      await resumeApi.uploadResumeFile(resumeId, formData)
    }

    ElMessage.success('简历上传成功')
    emit('success')
    handleClose()

  } catch (error) {
    ElMessage.error('上传失败')
  } finally {
    creating.value = false
  }
}

// 处理生成确认
const handleGenerateConfirm = async () => {
  if (!generateFormRef.value) return

  try {
    await generateFormRef.value.validate()
    
    creating.value = true

    const resumeData = {
      title: generateForm.title,
      resume_type: 'generated' as const,
      template: generateForm.template
    }

    await resumeApi.createResume(resumeData)

    ElMessage.success('简历创建成功')
    emit('success')
    handleClose()

  } catch (error) {
    ElMessage.error('创建失败')
  } finally {
    creating.value = false
  }
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
}

// 生命周期
onMounted(() => {
  // 预加载模板列表
  fetchTemplateList()
})
</script>

<style lang="scss" scoped>
.create-resume-dialog {
  .creation-methods {
    margin-bottom: 24px;

    .method-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin-bottom: 16px;
    }

    .method-options {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;

      .method-card {
        border: 2px solid var(--border-color-light);
        border-radius: 8px;
        padding: 20px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          border-color: var(--color-primary-light-7);
        }

        &.active {
          border-color: var(--color-primary);
          background: var(--color-primary-light-9);
        }

        .method-icon {
          color: var(--color-primary);
          margin-bottom: 12px;
        }

        .method-name {
          font-size: 16px;
          font-weight: 600;
          color: var(--text-color-primary);
          margin-bottom: 8px;
        }

        .method-desc {
          font-size: 14px;
          color: var(--text-color-secondary);
          line-height: 1.4;
        }
      }
    }
  }

  .upload-form, .generate-form {
    .upload-tip {
      font-size: 12px;
      color: var(--text-color-placeholder);
      margin-top: 4px;
    }

    .template-selector {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 16px;
      max-height: 300px;
      overflow-y: auto;

      .template-card {
        border: 2px solid var(--border-color-light);
        border-radius: 8px;
        padding: 12px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          border-color: var(--color-primary-light-7);
        }

        &.active {
          border-color: var(--color-primary);
          background: var(--color-primary-light-9);
        }

        .template-preview {
          width: 100%;
          height: 120px;
          border-radius: 4px;
          overflow: hidden;
          margin-bottom: 8px;
          background: var(--fill-color-extra-light);
          display: flex;
          align-items: center;
          justify-content: center;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .template-placeholder {
            color: var(--text-color-placeholder);
            font-size: 32px;
          }
        }

        .template-info {
          .template-name {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-color-primary);
            margin-bottom: 4px;
          }

          .template-desc {
            font-size: 12px;
            color: var(--text-color-secondary);
            line-height: 1.3;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .create-resume-dialog {
    .creation-methods {
      .method-options {
        grid-template-columns: 1fr;
      }
    }

    .template-selector {
      grid-template-columns: 1fr !important;
    }
  }
}
</style>
